package com.heisenhub.common.oauth.holder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.heisenhub.common.oauth.adapter.MyGrantedAuthorityAdapter;
import com.heisenhub.common.oauth.entity.UuaUser;
import com.heisnenhub.common.module.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.LinkedHashMap;

@Slf4j
public class LoginUserHolder {

    /**
     * 获取用户信息
     *
     * @return MyResUser 当前用户信息
     */
    public static UuaUser loginUser() {
        try {
            LinkedHashMap<String, Object> authenticationDetails = getAuthenticationDetails();
            Object principal = authenticationDetails.get("principal");

//            GsonBuilder gsonBuilder = new GsonBuilder();
//           gsonBuilder.registerTypeAdapter(GrantedAuthority.class, new MyGrantedAuthorityAdapter());
//           Gson gson = gsonBuilder.create();
//            String json = gson.toJson(principal);
//            return    gson.fromJson(json, UuaUser.class);
            Gson gson = GsonUtils.gsonBuilder(GrantedAuthority.class, new MyGrantedAuthorityAdapter());
            String json = gson.toJson(principal);
            return    gson.fromJson(json, UuaUser.class);
        //    return GsonUtils.objToBean(principal, UuaUser.class);
        } catch (Exception e) {
            log.info("获取当前用户信息失败", e);
            return null;
        }
    }




    /**
     * 通过  上下文对象
     * @return
     */
    public static OAuth2Authentication getOauth2Authentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (OAuth2Authentication) authentication;
    }

    @SuppressWarnings("all")
    private static LinkedHashMap<String, Object> getAuthenticationDetails() {
        return (LinkedHashMap<String, Object>) getOauth2Authentication().getUserAuthentication().getDetails();
    }


}
